#!/usr/bin/env python3
# coding: utf-8
"""
2024-02-04 harrydeep@wardyan.top 配置相关
"""

import configparser
 
from loguru import logger


"""
# 创建ConfigParser对象
config = configparser.ConfigParser()
 
# 读取配置文件
config.read('config.ini')
 
# 获取配置项的值
value = config.get('section', 'option')
 
# 更新配置项的值
config.set('section', 'option', 'new_value')
 
# 写入到配置文件
with open('config.ini', 'w') as configfile:
    config.write(configfile)
"""

class Config :
    """
    2024-02-04 读取配置文件
    """
    # 创建ConfigParser对象
    cfg = configparser.ConfigParser()
    
    # 读取配置文件，注意顺序很重要，后面的会覆盖前面的同名配置
    cfg.read("config\\config.ini", encoding="utf-8")
    cfg.read("config\\config-pro.ini", encoding="utf-8")
    cfg.read("config\\config-dev.ini", encoding="utf-8")
    # 优先读取dbconfig.ini，因为它包含具体的数据库配置
    cfg.read("config\\dbconfig.ini", encoding="utf-8")
    
    # # 获取配置项的值
    # value = cfg.get('section', 'option')
    
    # # 更新配置项的值
    # config.set('section', 'option', 'new_value')
    
    # # 写入到配置文件
    # with open('config.ini', 'w') as configfile:
    #     config.write(configfile)

    def get(self, section : str, key : str) :
        """
        读取配置值
        section : 
        key :
        """
        if self.cfg.has_section(section) and self.cfg.has_option(section=section, option=key) :
            return self.cfg.get(section, key)
        else :
            return None

    
config = Config()

def getconfig(section : str, key : str) :
    return config.get(section=section, key=key)


def getconfig_int(section : str, key : str) :
    rs = 0
    value = getconfig(section=section, key=key)
    if value is not None:
        try :
            rs = int(value)
        except :
            logger.warning("无效的配置项目:{} {}", section, key)
    ## print(section, key, rs)
    return rs


def getconfig_str(section : str, key : str) :
    rs = ""
    value = getconfig(section=section, key=key)
    if value is not None:
        try :
            rs = str(value)
        except :
            logger.warning("无效的配置项目:{} {}", section, key)
    return rs


def getconfig_bool(section : str, key : str) :
    rs = False
    value = getconfig(section=section, key=key)
    if value is not None:
        try :
            # 把字符串False转为布尔值
            # rs = bool(a)
            if str.lower(value) == "false" :
                rs = False
            else :
                rs = True
        except :
            logger.warning("无效的配置项目:{} {}", section, key)
    return rs


if __name__ == '__main__':
    c = Config()
    print(c)
    print(c.get("db", "host"))
    print(c.get("db", "test"))